package com.vivo.tasks;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.vivo.Utils.SysUtils;
import com.vivo.common.DatabaseContextHolder;
import com.vivo.employee.entity.ViEmployee;
import com.vivo.employee.service.ViEmployeeService;
import com.vivo.fx.employee.entity.FxEmployeeinfo;
import com.vivo.fx.employee.service.FxEmployeeinfoService;
import com.vivo.fx.sys.entity.FxUserinfo;
import com.vivo.fx.sys.service.FxUserinfoService;
import com.vivo.system.entity.SysRolePost;
import com.vivo.system.service.SysRolePostService;
import com.vivo.tasks.vivofx.Helper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 更新所有在职用户信息
 */
@Component
public class TaskUpdOndutyEmp {


    @Autowired
    private ViEmployeeService viEmployeeService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private SysRolePostService rolePostService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private FxUserinfoService fxUserinfoService;

    @Autowired
    private FxEmployeeinfoService fxEmployeeinfoService;

    private Map<String, String> officeMap;

    private Map<String, String> PeopleDict;

    /**
     * 同步一下用户信息，从用户信息侧进行查找没有的用户
     */
    public void sync() {
        getEmployeeInfo("ah");
        getEmployeeInfo("js");
    }


    private void getEmployeeInfo(String area) {
        officeMap = new HashMap<String, String>();

        List<Office> officesList = officeService.findMyOwnAllList();
        for (Office of : officesList) {
            officeMap.put(of.getId(), of.getName());
        }
        System.out.println("get office list size is:" + officesList.size());

        PeopleDict = new HashMap<String, String>();

        PeopleDict.put("EC180C3A50074365841ADA93756C7841", "3");
        PeopleDict.put("5ABBE292AE384E40ACD40E5AD01F71DA", "1");
        PeopleDict.put("C8EC6BE7782A4D2784791B1F3576DCDD", "2");

        PeopleDict.put("B76B77E89F6D47C29EEC9082B279429", "3");
        PeopleDict.put("220BB509254246E985A6FEA4A2060DAD", "1");
        PeopleDict.put("928B3F2CFD3F4B36A09FD704682BA06B", "2");


        System.out.println("get employee info from " + area + " ...");

        try {
            int pageStart = 1;

            Page<FxEmployeeinfo> page = new Page<FxEmployeeinfo>(pageStart, 3000);
            FxEmployeeinfo fxEQuery = new FxEmployeeinfo();
            fxEQuery.setEmployeecurrstateid("2");

            Helper.changeDB(area);
            Page<FxEmployeeinfo> pageRes = fxEmployeeinfoService.findPage(page, fxEQuery);

            // 切换数据库
            DatabaseContextHolder.setMainDb();
            handleEmployee(pageRes.getList(), area);

            System.out.println("page count is : " + pageRes.getTotalPage());

            for (int i = pageStart; i <= pageRes.getTotalPage(); i++) {
                System.out.println("cur page is :" + pageRes.getPageNo() + " and pageSize is :" + pageRes.getPageSize());
                page.setPageNo(i);

                Helper.changeDB(area);
                pageRes = fxEmployeeinfoService.findPage(page, new FxEmployeeinfo());

                DatabaseContextHolder.setMainDb();
                handleEmployee(pageRes.getList(), area);
            }

        } finally {
            DatabaseContextHolder.setMainDb();
        }

        System.out.println("get employee info from " + area + " end !");
    }


    private void handleEmployee(List<FxEmployeeinfo> empList, String area) {
        for (FxEmployeeinfo fxEmp : empList) {
            String employeeId = fxEmp.getEmployeeid();

            // 查看系统中是否存在该用户
            ViEmployee ve = viEmployeeService.get(employeeId);
            if (ve == null) {
                // 系统中不存在该用户，进行添加操作
                System.out.println("添加新员工：" + fxEmp.getEmployeename());
                saveNewEmployee(fxEmp, area);
            } else {
                // 系统中存在用户，进行更新操作

                // 如果IDC中为离职，则修改离职信息
                if (!ve.getCurStateId().equals("2")) {
                    ve.setCurStateId(fxEmp.getEmployeecurrstateid());
                    ve.setOutdutyDate(fxEmp.getOutdutydate());
                    ve.setTelephone(fxEmp.getTelephone());
                    viEmployeeService.save(ve);

                    System.out.println("修改离职人员为在职人员，： " + ve.getName());
                }

                saveUserInfoByVe(ve, area);
            }
        }
    }


    private void saveUserInfoByVe(ViEmployee viEmployee, String area) {
        do {
//            Office comp = officeService.get(viEmployee.getComp().getId());
            String zone = area;

            FxUserinfo sysUser = null;
            User user = null;
            try {
                //  获取用户登陆信息
                user = systemService.getUserByEmpId(viEmployee.getId());
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }

            try {
                // 根据区域切换数据库
                Helper.changeDB(zone);

                sysUser = fxUserinfoService.getByEmpId(viEmployee.getId());
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            } finally{
                DatabaseContextHolder.setMainDb();
            }

            if (sysUser == null) {
                continue;
            }

            if (user != null && sysUser.getUserid().equals(user.getId())) {
                continue;
            }

            // TODO 获取用户权限信息


            // 替换用户的ID信息， 包括如下信息
            // 用户ID修改， 用户菜单ID修改， 用户角色iD修改，用户权限ID修改
            if (user != null) {
                user.setNewUid(sysUser.getUserid());
                user.setOldUid(user.getId());

                // 更新用户数据
                try {
                    systemService.updVivoUser(user);
                    System.out.println("更新用户ID信息，IDC的UID：" + user.getId() + " , vivo的UID：" + sysUser.getUserid());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                // 添加新用户
                System.out.println("添加用户信息：" + viEmployee.getName());
                addNewUserByVe(viEmployee, area, sysUser);
            }
        } while (false);
    }


    private boolean addNewUserByVe(ViEmployee viEmployee, String area, FxUserinfo fxUser) {
        boolean retFlag = true;
        // 获取职位对应角色
        SysRolePost rolePost = new SysRolePost();
        Role role = null;
        rolePost.setPost(viEmployee.getPostName());
        List<SysRolePost> rolePostList = rolePostService.findList(rolePost);
        if (rolePostList.size() > 0) {
            role = rolePostList.get(0).getRole();
        } else {
//                rolePost.setPost("无角色");
//                rolePostList = rolePostService.findList(rolePost);
//                if (rolePostList.size() > 0) {
//                    role = rolePostList.get(0).getRole();
//                }
            role = systemService.getRoleByName("无角色");
        }

        String password = "123456";
        if (viEmployee.getTelephone().length() == 11) {
            password = viEmployee.getTelephone().substring(5, 11);
        }
        System.out.println("password is :" + password);

        User user = new User();
        user.setPassword(SystemService.entryptPassword(password));
        // 优信通同步密码和盐
        user.setSysSalt(SysUtils.createSalt());
        user.setSysPwd(SysUtils.getPwdBySalt(password, user.getSysSalt()));

//                    user.setEmployeeId(fe.getEmployeeid());
        user.setOffice(viEmployee.getDept());
        user.setPosition(viEmployee.getPost());
        user.setCompany(viEmployee.getComp());
        user.setMobile(viEmployee.getTelephone());
        user.setPhone(viEmployee.getTelephone());
        user.setLoginName(viEmployee.getTelephone());
        user.setName(viEmployee.getName());
        user.setNo(viEmployee.getCode());
        user.setEmployeeId(viEmployee.getId());
        user.setId(fxUser.getUserid());
        user.setIsNewRecord(true);
        user.setIsTaskInsert(true);

        try {
            if (role != null) {
                user.setRole(role);
                List<Role> rl = new ArrayList<Role>();
                rl.add(role);
                user.setRoleList(rl);
            }
            systemService.saveUser(user);

            // 设置用户角色
            if (role != null) {
                systemService.assignUserToRole(role, user);
            }
        } catch (Exception e) {
            viEmployee.setErrMsg(e.getMessage());
            e.printStackTrace();

            retFlag = false;
        }

        return retFlag;
    }


    private boolean saveNewEmployee(FxEmployeeinfo fe, String area) {
        boolean retFlag = true;

        Office company = new Office();
        Office office = new Office();
        Office postion = new Office();

        ViEmployee sp = new ViEmployee();

        String employeeId = fe.getEmployeeid();
        String superId = fe.getSuperioremployeeid();
//            if (area.equals("ah")) {
//                employeeId = employeeId.toLowerCase();
//                if (superId != null) {
//                    superId = superId.toLowerCase();
//                }
//            }
        ViEmployee ve = viEmployeeService.get(employeeId);

        company.setId(fe.getCompanyid());
        office.setId(fe.getDepartmentid());
        postion.setId(fe.getPositionid());

        String postName = officeMap.get(fe.getPositionid());

        sp.setId(superId);

        if (ve == null) {
            ve = new ViEmployee();
            ve.setIsTaskInsert(true);
            ve.setPostName(postName);

//                ve.setId(fe.getEmployeeid());
            ve.setId(employeeId);
            ve.setComp(company);
            ve.setDept(office);
            ve.setPost(postion);
            ve.setCode(fe.getEmployeecode());

            ve.setName(fe.getEmployeename());
            ve.setSex(fe.getSex());
            ve.setEducateId(fe.getEducationid());
            ve.setAge(fe.getAge());
            ve.setBirthDate(fe.getBirthdaydate());

            ve.setTelephone(fe.getTelephone());
            ve.setIdentityCard(fe.getIdentitycard());
            ve.setIndutyDate(fe.getIndutydate());

            String empAttrStr = "2";
            if (fe.getPeopleattribute() != null) {
                empAttrStr = PeopleDict.get(fe.getPeopleattribute());
                if (empAttrStr == null) {
                    empAttrStr = "2";
                }
            }
//                System.out.println(empAttrStr);
            ve.setEmpAttribute(empAttrStr);

            ve.setDgAttribute(fe.getEmployeeattribute());


            ve.setCurStateId(fe.getEmployeecurrstateid());

            ve.setCensusRegister(fe.getCensusregister());
            ve.setAddress(fe.getAddress());
            ve.setRemarks(fe.getRemarks());
            ve.setSp(sp);
            ve.setSchool(fe.getSchool());

            ve.setProfessional(fe.getProfessional());
            ve.setEmergencyName(fe.getEmergencycontactname());
            ve.setEmergencyPhone(fe.getEmergencycontactphone());
            ve.setProfessional(fe.getProfessional());
            ve.setWageBase(fe.getWagebase());

            ve.setSocialNo(fe.getSocialnumber());
            ve.setSocialCurMoney(fe.getSocialcurrmoney());
            ve.setOutdutyDate(fe.getOutdutydate());

            ve.setCardNo(fe.getCardno());
            ve.setDepositBank(fe.getDepositbank());

            ve.setMaritalStatus(fe.getMaritalstatus());

            ve.setClothesSizeId(fe.getClothessizeid());

            ve.setZone(area);

            try {
                viEmployeeService.save(ve);
            } catch (Exception e) {
                e.printStackTrace();
                retFlag = false;
            }

        } else {
            // 查看是否离职
            if (fe.getOutdutydate() != null) {
                ve.setOutdutyDate(fe.getOutdutydate());
                ve.setBeginOutdutyDate(fe.getOutdutyoperatetime());
                try {
                    viEmployeeService.save(ve);
                } catch (Exception e) {
                    e.printStackTrace();
                    retFlag = false;
                }
            }

            System.out.println("has exists with: " + employeeId + "   area is :" + area);
        }

        FxUserinfo sysUser = null;
        if (retFlag) {
            // 添加用户信息
            try {
                // 根据区域切换数据库
                Helper.changeDB(area);

                sysUser = fxUserinfoService.getByEmpId(fe.getEmployeeid());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                DatabaseContextHolder.setMainDb();
                retFlag = false;
            }

            if (sysUser != null) {
                retFlag = addNewUserByVe(ve, area, sysUser);
            }
        }

        return retFlag;
    }

}